package com.mms.utsc.smartnet;

import java.util.Calendar;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceFragment;
import android.widget.Toast;

public class FragmentPreferences extends Activity {

	CheckBoxPreference enableUpdate;
	Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		context = this;
		getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragment()).commit();

	}

	class PrefsFragment extends PreferenceFragment implements OnPreferenceChangeListener {

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);

			// Load the preferences from an XML resource
			addPreferencesFromResource(R.xml.preferences);

			enableUpdate = (CheckBoxPreference) findPreference("enable_update");
			enableUpdate.setOnPreferenceChangeListener(this);
		}

		@Override
		public boolean onPreferenceChange(Preference pref, Object newVal) {
			// TODO Auto-generated method stub
			UpdateAnnouncements update = new UpdateAnnouncements();
			update.cancelSchedUpdate(context);
			if ((Boolean) newVal) {
				String currTime = PreferenceManager.getDefaultSharedPreferences(context).getString("update_time", "00:00");

				Calendar timeToTrigger = Calendar.getInstance();
				timeToTrigger.set(timeToTrigger.get(Calendar.YEAR), timeToTrigger.get(Calendar.MONTH), timeToTrigger.get(Calendar.DAY_OF_MONTH), TimePickerPref.getHour(currTime),
						TimePickerPref.getMinute(currTime));
				update.schedUpdate(context, timeToTrigger.getTimeInMillis());
			}

			return true;
		}
	}
}
